<template>
  <div class='content'>
    <div class='title'>
      <div class='op'></div>
      基本信息
    </div>
    <a-form :form='form' :label-col='{ span: 5 }' :wrapper-col='{ span: 12 }' @submit='handleSubmit' ref='basicForm'>
      <a-form-item label='项目名称'>
        <a-input
          v-decorator="['projectName', {initialValue: formData.projectName, rules: [{ required: true, message: '请输入项目名称' }] }]" />
      </a-form-item>
      <a-form-item label='项目编号'>
        <a-input
          v-decorator="['projectId', {initialValue: formData.projectId, rules: [{ required: true, message: '请输入项目编号' }] }]" />
      </a-form-item>
      <a-form-item label='项目来源'>
        <a-select
          v-decorator="['projectSource', {initialValue: formData.projectSource , rules: [{ required: true, message: '请选择项目来源' }]}]"
          placeholder='请选择'>
          <a-select-option :value=0>国家省部级</a-select-option>
          <a-select-option :value=1>集团公司级</a-select-option>
          <a-select-option :value=2>海油发展重大专项</a-select-option>
          <a-select-option :value=3>海油发展重点攻关</a-select-option>
          <a-select-option :value=4>海油发展常规</a-select-option>
          <a-select-option :value=5>采油公司级</a-select-option>
        </a-select>
      </a-form-item>
      <a-form-item label='父级项目名称'>
        <a-input
          v-decorator="['parentName', {initialValue: formData.parentName }]" />
      </a-form-item>
      <div style='position: relative'>
        <a-form-item :label='item.label' v-for='(item, index) in danweiList' :key='index'>
          <a-tree-select
            v-model="item.value"
            :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
            :tree-data='treeData'
          >
            <span slot='title' slot-scope='{  value }' style='color: #08c'>
               {{ value }}
            </span>
          </a-tree-select>
          <!-- 只有当 danweiList 的长度大于 1 时，才显示删除链接 -->
          <a v-if="index > 0 && danweiList.length > 1" href='javascript:;' @click="removeDanwei(index)" style='position: absolute; right: -8%;bottom:-12px'>删除</a>
        </a-form-item>
        <a href='javascript:;' style='position: absolute; right: 25%;top:10px' @click='addDanwei'>新增</a>
      </div>


      <a-form-item label='项目状态'>
        <a-select
          v-decorator="['status', {initialValue: formData.status, rules: [{ required: true, message: '请选择项目状态' }] }]"
          placeholder='请选择'
        >
          <a-select-option :value='0'>筹备中</a-select-option>
          <a-select-option :value='1'>立项中</a-select-option>
          <a-select-option :value='2'>实施中</a-select-option>
          <a-select-option :value='3'>已完结</a-select-option>
        </a-select>
      </a-form-item>
      <a-form-item label='项目周期'>
        <div style='display: flex'>
          <a-date-picker
            v-decorator="['cycleStart',{initialValue: formData.cycleStart, rules: [{ required: true, message: '请选择开始日期' }] }]" />
          <span style='margin: 0 5px'>~</span>
          <a-date-picker
            v-decorator="['cycleEnd',{initialValue: formData.cycleEnd, rules: [{ required: true, message: '请选择结束日期' }] }]" />
        </div>
      </a-form-item>
      <a-form-item label='项目经理/课题负责人'>
        <a-input
          v-decorator="['manager', {initialValue: formData.manager, rules: [{ required: true, message: '请输入姓名' }] }]" />
      </a-form-item>
      <a-form-item label='项目总预算'>
        <a-input placeholder='自动带出'
        disabled
        v-decorator="['budget', {
          initialValue: formData.budget,
      }]"
                   />
      </a-form-item>
      <a-form-item label='项目类型'>
        <a-select
          v-decorator="['type', { initialValue: formData.type,rules: [{ required: true, message: '请选择项目类型' }] }]"
          placeholder='请选择'
        >
          <a-select-option :value='0'> 科技项目</a-select-option>
          <a-select-option :value='1'> 英才计划</a-select-option>
          <a-select-option :value='2'> 三新三化项目</a-select-option>
          <a-select-option :value='3'> 标准化项目</a-select-option>

        </a-select>
      </a-form-item>
      <a-form-item label='WBS订单号'>
        <a-input
          v-decorator="['wbsId', {initialValue: formData.wbsId, rules: [{ required: true, message: '请输入WBS订单号' }] }]" />
      </a-form-item>
      <a-form-item label='下文文号'>
        <a-input
          v-decorator="['contextSymbol', {initialValue: formData.contextSymbol, rules: [{  message: '请输入下文文号' }] }]" />
      </a-form-item>
      <a-form-item label='技术领域'>
        <a-select
          v-decorator="['technicalfield', {initialValue: formData.technicalfield, }]"
          placeholder='请选择'
        >
          <a-select-option :value='0'> FPSO</a-select-option>
          <a-select-option :value='1'> 边际油田</a-select-option>
          <a-select-option :value='2'> 系泊</a-select-option>
          <a-select-option :value='3'> LNG</a-select-option>
          <a-select-option :value='4'> 非常规</a-select-option>
          <a-select-option :value='5'> 生产技术服务</a-select-option>
          <a-select-option :value='6'> 数字化</a-select-option>
          <a-select-option :value='7'> 其他</a-select-option>
        </a-select>
      </a-form-item>
      <a-form-item label='所属专业'>
        <a-select
          v-decorator="['major', {initialValue: formData.major, }]"
          placeholder='请选择'
        >
          <a-select-option :value='0'> FPSO</a-select-option>
          <a-select-option :value='1'> 边际油田</a-select-option>
          <a-select-option :value='2'> 系泊</a-select-option>
          <a-select-option :value='3'> LNG</a-select-option>
          <a-select-option :value='4'> 非常规</a-select-option>
          <a-select-option :value='5'> 生产技术服务</a-select-option>
          <a-select-option :value='6'> 数字化</a-select-option>
          <a-select-option :value='7'> 其他</a-select-option>
        </a-select>
      </a-form-item>
      <a-form-item label='主要专业'>
        <a-select
          v-decorator="['majorSpecialty', {initialValue: formData.majorSpecialty ,}]"
          placeholder='请选择'
        >
          <a-select-option :value='0'> FPSO</a-select-option>
          <a-select-option :value='1'> 边际油田</a-select-option>
          <a-select-option :value='2'> 系泊</a-select-option>
          <a-select-option :value='3'> LNG</a-select-option>
          <a-select-option :value='4'> 非常规</a-select-option>
          <a-select-option :value='5'> 生产技术服务</a-select-option>
          <a-select-option :value='6'> 数字化</a-select-option>
          <a-select-option :value='7'> 其他</a-select-option>
        </a-select>
      </a-form-item>
      <a-form-item label='次要专业'>
        <a-select
          v-decorator="['minorMajor', { initialValue: formData.minorMajor,  }]"
          placeholder='请选择'
        >
          <a-select-option :value='0'> FPSO</a-select-option>
          <a-select-option :value='1'> 边际油田</a-select-option>
          <a-select-option :value='2'> 系泊</a-select-option>
          <a-select-option :value='3'> LNG</a-select-option>
          <a-select-option :value='4'> 非常规</a-select-option>
          <a-select-option :value='5'> 生产技术服务</a-select-option>
          <a-select-option :value='6'> 数字化</a-select-option>
          <a-select-option :value='7'> 其他</a-select-option>
        </a-select>
      </a-form-item>
      <a-form-item :wrapper-col='{ span: 12, offset: 5 }' style='margin-bottom: 80px;'>
        <a-button type='primary' id='submit-basic-info-btn' html-type='submit' @click='nextTab'> 下一步</a-button>
      </a-form-item>
    </a-form>
  </div>
</template>

<script>
import { getDept, addProject, detail, modifyProject } from '@/api/projectInitApply'

export default {

  data() {
    return {
      formLayout: 'horizontal',
      form: this.$form.createForm(this, { name: 'coordinated' }),
      danweiList: [{
        label: '承担单位',
        value: null
      }],
      formData: {},
      unitData:null,
      treeData: null,
      projectId: null,
      triggerFromExternal: false
    }
  },

  mounted() {
    this.getById()
    getDept().then(res => {
      console.log(res)
      if (res.code === 200) {
        this.treeData = this.geneTree([res.data])
        console.log(this.treeData)
      }
    })

  },
  methods: {
    getById() {
      if (this.$route.query.id) {
        detail({ id: this.$route.query.id }).then(res => {
          res.data.cycleTime = res.data.cycleStart + '~' + res.data.cycleEnd
          this.formData = res.data
          console.log(1233, this.formData)
        })
      }
    },
    formatDateString(inputDateString) {
      const inputDate = new Date(inputDateString)

      // 获取年、月、日
      const year = inputDate.getFullYear()
      const month = String(inputDate.getMonth() + 1).padStart(2, '0') // 月份从0开始，需要加1
      const day = String(inputDate.getDate()).padStart(2, '0')
      // 拼接成规范的日期格式
      const formattedDate = `${year}-${month}-${day}`
      return formattedDate
    },
    submitTrigger() {
      console.log("哼哼")
      this.triggerFromExternal = true
      document.getElementById('submit-basic-info-btn').click()
    },
    async nextTab(e) {
      if (e) {
        e.preventDefault()
      }
      const _this = this
      const validateFieldsPromise = () => new Promise((resolve, reject) => {
        this.form.validateFields((err, values) => {
          if (err) {
            reject(false)
          } else {
            resolve(values)
          }
        })
      })
      // 等待 validateFields 方法完成
      const values = await validateFieldsPromise().catch(err => err)
      if (values) {
        console.log('values', values)
        if(this.danweiList.length>0){
          let list =[]
         list= this.danweiList.map(ele=>{
            return {
              key:ele.value
            }
          })
        values.unitList = list;
        }
        values.cycleStart = this.formatDateString(values.cycleStart)
        values.cycleEnd = this.formatDateString(values.cycleEnd)
        values.id = this.formData.id
        if (this.$route.query.id) {
          modifyProject(values).then(res => {
            if (res.code == 200) {
              console.log(res.data)
              _this.$emit('projectId', res.data)
              _this.$emit('next', 1)
            } else {
              this.$message.error(res.msg)
            }
          }).catch(err => {
            this.$message.error(err)
          })
        } else {
          addProject(values).then(res => {
            if (res.code == 200) {
              console.log(res.data)
              values.id = res.data
              localStorage.setItem("basicInfo", JSON.stringify(values))
              if (this.triggerFromExternal) {
                this.$router.push({ path: '/initManage' })
              } else {
                _this.$emit('projectId', res.data)
                _this.$emit('next', 1)
              }
            } else {
              this.$message.error(res.msg)
            }
          }).catch(err => {
            this.$message.error(err)
          })
        }
        console.log('Received values of form: ', values)
      } else {
        console.error('Error in form validation:')
      }
    },
    geneTree(data, res) {
      return data.map(ele => {
        if (ele.children && ele.children.length > 0) {
          return {
            title: ele.title,
            key: ele.id,
            value: ele.id,
            children: this.geneTree(ele.children)
          }
        } else {
          return {
            title: ele.title,
            key: ele.id,
            value: ele.id,
            children: []
          }
        }
      })
    },

    addDanwei() {
      this.danweiList.push({
        label: `承担单位${this.danweiList.length}`,
        value:null
      })
    },
    removeDanwei(index) {
    this.danweiList.splice(index, 1);
  },
    handleSubmit(e) {
      // e.preventDefault();
      // 使用 Promise 包装 validateFields 方法

    }

  }
}
</script>


<style lang='less' scoped>
.content {
  height: 100%;
  width: 100%;
  padding-left: 220px;
  padding-top: 10px;

  .title {
    height: 30px;
    display: flex;
    align-items: center;
    margin-left: -200px;

    .op {
      height: 20px;
      width: 5px;
      background: #0084ff;
      margin-right: 10px;
    }
  }
}
</style>
